﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace System.Text
{
    public static class RegexExt
    {
        /// <summary>
        /// 解析 a 标签中的URL内容
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetHref(this string str)
        {
            var item = GetRegexResult(str, @"<a[^>]*href=([""'])?(?<href>[^'""]+)\1[^>]*>");
            return item.Groups["href"].Value;
        }

        /// <summary>
        /// 获取URL中的 host
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetUrlHost(this string str)
        {
            var item = GetRegexResult(str, "(http://|https://)(.*?)/");
            ///这里需要是 item.Groups[1]
            ///因为item.Groups[0] 匹配的是  正则表达式
            return item.Groups[1].Value + item.Groups[2].Value;
        }


        /// <summary>
        /// 输出解析出来的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        public static string AnalyseRegexResult(this string str, string rule)
        {
            var item = GetRegexResult(str, rule);
            ///这里需要是 item.Groups[1]
            ///因为item.Groups[0] 匹配的是  正则表达式
            return item.Groups[1].Value;
        }


        private static Match GetRegexResult(string str, string rule)
        {
            Match item = Regex.Match(str, rule, RegexOptions.IgnoreCase);
            return item;
        }


    }
}
